<?php
/**
 * @file $HeadURL: piccategory.php $
 * @author $Author: LiangJian (liangjian@haibao.com) $
 * @date $Date: 2014-12-9 下午7:12:24 $
 * @brief 
 */
namespace haibao\cms\data;

use haibao\frame\data\query\Condition;
use \haibao\cms\model\data\ImageCategoryDefine as CategoryModelData;
use \haibao\cms\model\filter\ImageCategoryDefine as CategoryModelFilter;

class ImageCategoryDefine extends \haibao\cms\data\BaseMysql{
	
	public function __construct(){
		parent::__construct('\haibao\cms\model\data\ImageCategoryDefine');
	}
	
	/**
	 * 
	 */
	public function searchCategoryByName($name){
	    $sql = 'select Id,CategoryName from ImageCategoryDefine where CategoryName like %s limit 10';
	    $result = $this->query($sql,array('%'.$name.'%'));
	    $category = array();
	    while($row = $result->fetch_assoc()){
	        $category[] = $row;
	    }
	    return $category;
	}
	
	/**
	 * @param \haibao\cms\model\data\ImageCategoryDefine $model
	 */
	public function getCategoryById($id){
		return $this->getOneById($id);
	}
	
	/**
	 * @param \haibao\cms\model\data\ImageCategoryDefine $model
	 */
	public function addCategory($model){
		$this->add($model);
		$this->delCacheAllCategorys();
	}
	
	/**
	 * @param \haibao\cms\model\data\ImageCategoryDefine $model
	 */
	public function updateCategoryById($model){
		$arrSet = array();
		if($model->CategoryName){
			$arrSet[CategoryModelFilter::CONDITION_FIELD_NAME_CATEGORYNAME] = $model->CategoryName;
		}
		if($model->ParentId){
			$arrSet[CategoryModelFilter::CONDITION_FIELD_NAME_PARENTID] = $model->ParentId;
		}
		if($model->OrderNo){
			$arrSet[CategoryModelFilter::CONDITION_FIELD_NAME_ORDERNO] = $model->OrderNo;
		}
		$this->updateById($model->Id, $arrSet);
		
		$this->delCacheAllCategorys();
	}
	
	/**
	 * @param \haibao\cms\model\data\ImageCategoryDefine $model
	 */
	public function deleteImageCategoryDefineById($id){
		$this->beginTranscation();
		try {
			$model = $this->getCategoryById($id);
			
			$childIds = $this->getChildCategoryById($id);
			array_unshift($childIds, $id);
			$str = preg_replace('/(\d+)/', '%s', implode(',', $childIds));
			
			$sql = 'update `ImageCategoryDefine` set Status=%s where id in('.$str.')';
			
			array_unshift($childIds, CategoryModelData::STATUS_DISABLE);
			$this->query($sql, $childIds);
			
			$this->delCacheAllCategorys();
		} catch (\Exception $e) {
			$this->rollback();
			throw $e;
		}
		$this->endTranscation();
	}
	
	public function getMaxOrderId($parentId){
		$max = null;
		$sql = 'select max(OrderNo) as max from ImageCategoryDefine where ParentId=%s and status=%s';
		$result = $this->query($sql, array(
				$parentId, CategoryModelData::STATUS_ENABLE
			));
		while ($result->fetch_assoc()) {
			$max = $result->getData('max');
		}
		return $max;
	}
	
	/**
	 * @param int $id 需要排除的id
	 */
	public function getCategoryByName($categoryName, $excludeId = null){
		$query = new CategoryModelFilter();
		$query->where(\haibao\cms\model\filter\ImageCategoryDefine::CONDITION_FIELD_NAME_CATEGORYNAME, Condition::CONDITION_EQUAL, $categoryName);
		if($excludeId){
			$query->where(\haibao\cms\model\filter\ImageCategoryDefine::CONDITION_FIELD_NAME_ID, Condition::CONDITION_NOTIN, (array)$excludeId);
		}
		$query->limit(1);
		
		return $this->getAll($query);
	}
	
	public function getCategoryTree(){
		$arrTree = array();
		$allDict = $this->getAllCategorysDict();
		foreach($allDict as $val){
			if(isset($allDict[$val[CategoryModelFilter::CONDITION_FIELD_NAME_PARENTID]])){
				// 不使用分类id作为key值，避免json_encode对key做排序影响分类显示顺序
				$allDict[$val[CategoryModelFilter::CONDITION_FIELD_NAME_PARENTID]]['children'][] = &$allDict[$val[CategoryModelFilter::CONDITION_FIELD_NAME_ID]];
			}else{
				$arrTree[$val[CategoryModelFilter::CONDITION_FIELD_NAME_ID]] = &$allDict[$val[CategoryModelFilter::CONDITION_FIELD_NAME_ID]];
			}
		}
		return $arrTree;
	}
	
	public function getAllCategorysDict(){
		$query = new CategoryModelFilter();
		$query->where(\haibao\cms\model\filter\ImageCategoryDefine::CONDITION_FIELD_NAME_STATUS, Condition::CONDITION_EQUAL, CategoryModelData::STATUS_ENABLE);
		$query->order(\haibao\cms\model\filter\ImageCategoryDefine::CONDITION_FIELD_NAME_ORDERNO);
		$models = $this->getAll($query);
		
		$retArr = array();
		while (count($models)){
			$model = array_shift($models);
			$retArr[$model->Id] = $model->toArray();
		}
		
		return $retArr;
	}
	
	public function getCacheAllCategorys(){
		$cache = new \haibao\cms\cache\ImageLibrary();
		$allCategorys = $cache->getAllCategorys();
		if(!empty($allCategorys)){
			$allCategorys = json_decode($allCategorys,true);
		}
		
		return $allCategorys;
	}
	
	public function setCacheAllCategorys($allCategorys){
		$cache = new \haibao\cms\cache\ImageLibrary();
		$cache->setAllCategorys($allCategorys);
	}
	
	/**
	 * 根据父级分类id查询下级分类的id（新表）
	 */
	public function getChildCategoryById($id,$arrCategoryDefine = null){
		if(!$id){
			return false;
		}
		$query = new CategoryModelFilter();

		if(empty($arrCategoryDefine)){
			$arrCategoryDefine = $this->getAllCategorysDict();
		}
		$categoryList  = array();
		self::convertCategory($categoryList, $arrCategoryDefine,$id);
	
		if(isset($categoryList) && $categoryList){
			$query->where(\haibao\cms\model\filter\ImageCategoryDefine::CONDITION_FIELD_NAME_ID, Condition::CONDITION_OR, array(
					new Condition(\haibao\cms\model\filter\ImageCategoryDefine::CONDITION_FIELD_NAME_ID,Condition::CONDITION_EQUAL,$id),
					new Condition(\haibao\cms\model\filter\ImageCategoryDefine::CONDITION_FIELD_NAME_ID,Condition::CONDITION_IN,$categoryList),
			));
		}else {
			$query->where(\haibao\cms\model\filter\ImageCategoryDefine::CONDITION_FIELD_NAME_ID, Condition::CONDITION_EQUAL, $id);
		}
		
		$models = $this->getAll($query);
	
		$retArr = array();
		while (count($models)){
			$model = array_shift($models);
			$arrModel = $model->toArray();
			array_push($retArr, $arrModel[\haibao\cms\model\filter\ImageCategoryDefine::CONDITION_FIELD_NAME_ID]);
		}
		return $retArr;
	}
	
	public function getCategoryByNameAndParentId($categoryName, $parentId = 0){
		$query = new CategoryModelFilter();
		$query->where(\haibao\cms\model\filter\ImageCategoryDefine::CONDITION_FIELD_NAME_CATEGORYNAME, Condition::CONDITION_EQUAL, $categoryName);
		if($parentId){
			$query->where(\haibao\cms\model\filter\ImageCategoryDefine::CONDITION_FIELD_NAME_PARENTID, Condition::CONDITION_EQUAL, $parentId);
		}
		$query->limit(1);
	
		return $this->getOne($query);
	}

	private function delCacheAllCategorys(){
		$cache = new \haibao\cms\cache\ImageLibrary();
		$cache->delAllCategorys();
	}
	
	private function convertCategory(&$categoryList, $aCategory, $parentId = ''){
		foreach($aCategory as $key=>$list){
			if($list[\haibao\cms\model\filter\ImageCategoryDefine::CONDITION_FIELD_NAME_PARENTID] == $parentId){
				$categoryList[] = $list['Id'];
				self::convertCategory($categoryList, $aCategory, $list[\haibao\cms\model\filter\ImageCategoryDefine::CONDITION_FIELD_NAME_ID]);
			}
		}
	}
	
}